#include "exprNode.h"
#include <iostream>
#include "Error.h"

exprNode::exprNode(Lexer::Token_type tokType, exprNode* leftChild, exprNode* rightChild, double value1)
{
	type = tokType;
	left = leftChild;
	right = rightChild;
	value = value1;
}

double exprNode::getvalue()
{
	if (left != nullptr)
		left->getvalue();
	if (right != nullptr)
		right->getvalue();

	switch (type)	{
	case Lexer::PLUS:
		value = left->value + right->value;
		break;
	case Lexer::MINUS:
		value = left->value - right->value;
		break;
	case Lexer::MUL:
		value = left->value * right->value;
		break;
	case Lexer::DIV:
		if (right->value == 0)
			Error::error("Divided by 0");
		value = left->value / right->value;
		break;
	default:
		break;
	}//end of swich

	return value;
}


std::string exprNode::getText_mid() const
{
	bool left_prime = (type == Lexer::MUL || type == Lexer::DIV)
		&& (left->type == Lexer::PLUS || left->type == Lexer::MINUS);
	bool right_prime = (type == Lexer::MUL || type == Lexer::DIV)
		&& (right->type == Lexer::PLUS || right->type == Lexer::MINUS);
	std::string reStr;
	if (left_prime) reStr += "(";
	if (left != nullptr)
		reStr += left->getText_mid();
	if (left_prime) reStr += ")";

	if (type == Lexer::NUMBER) {
		char ch[20];
		sprintf_s(ch, "%g", value);
		reStr += ch;
	}
	else reStr += type;

	if (right_prime) reStr += "(";
	if(right!=nullptr)
		reStr += right->getText_mid();
	if (right_prime) reStr += ")";

	return reStr;
	
}

std::string exprNode::getText_pre() const
{
	std::string reStr;

	if (type == Lexer::NUMBER) {
		char ch[20];
		sprintf_s(ch, "%g ", value);
		reStr += ch;
	}
	else reStr += type;
	
	if(left!=nullptr)
		reStr += left->getText_pre();

	if(right!=nullptr)
		reStr += right->getText_pre();
	return reStr;
}

std::string exprNode::getText_post() const
{
	if (this == nullptr)return "";
	std::string reStr;
	if (left != nullptr)
		reStr += left->getText_post();
	if (right != nullptr)
		reStr += right->getText_post();
	if (type == Lexer::NUMBER) {
		char ch[20];
		sprintf_s(ch, "%g ", value);
		reStr += ch;
	}
		else reStr += type;
	return reStr;
}